import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Link } from 'react-router';
import {  Modal,Icon,Tabs,message,Table,Dropdown,Menu,Button,Input,Form ,Row,Col,Select,Switch,Popconfirm,Pagination,DatePicker,Spin} from 'antd';
const Search = Input.Search;
const Option = Select.Option;
import NavBar from '../common/NavBar';
import ContentBody from '../common/ContentBody';
import SearchPanel from '../common/SearchPanel';
import RemarkModal from '../common/RemarkModal';
import DataAnalyzeTable from '../common/DataAnalyzeTable';

import {ANALYZE_TABLE_TYPE} from '../constants/index';
import api from '../api';
import moment from 'moment';
import {bind_change, bind_toggle} from '../common/State';
const {RangePicker} = DatePicker


export default class RedeemReportList extends React.Component {
    constructor(props, context){
        super(props, context);
        this.state={
          loading:false,
          data:{
            assetReport:{},
            currentHappen:[],
            recycleAmount:[],
            endAsset:[],
            endAccumulate:[],
          },
          recycleAmountSubType:1,
          endTermAssetSubType:1,
          period:0,
          type:1,

           page:0,
           total:1,
           pageSize:10,
           list:[],
           search:{},
           searchFlag:true,
           visible:false,
           resetpwdId:null,
           session:{},
           remarkVisibility:false,
           submitPropertyVisility:false,
           period:"3",

        };
    }

     componentWillMount(){
      // let session = await this.props.route.session();
      // let {page,pageSize} = this.state
      // this.setState({
      //   session,
      // })
      let {period} = this.state;
      this.doFetch(period);
    }
     componentWillReceiveProps(nextProps){
        //  let session = await this.props.route.session();
        // this.setState({
        //   session
        // })
    }
    //查询列表
    async doFetch(period){

      this.setState({
        loading:true
      })
      let session =  this.props.route.session;
      let {type,data} = this.state
      let result = await api('/property/getAssetReport/All',{type,period});

      if (result.assetReport.success) {
        data.assetReport = result.assetReport.data;
      }else{
        message.error(result.assetReport.message)
      }

      if (result.currentHappen.success) {
        data.currentHappen = result.currentHappen.data;
      }else{
        message.error(result.currentHappen.message)
      }

      if (result.recycleAmount.success) {
        data.recycleAmount = result.recycleAmount.data;
      }else{
        message.error(result.recycleAmount.message)
      }

      if (result.endAsset.success) {
        data.endAsset = result.endAsset.data;
      }else{
        message.error(result.endAsset.message)
      }

      if (result.endAccumulate.success) {
        data.endAccumulate = result.endAccumulate.data;
      }else{
        message.error(result.endAccumulate.message)
      }

      this.setState({
        data,
        loading:false,
        period,
        session,
      })

      // if(result.cd==0){
      //     this.setState({
      //       total:result.total,
      //       list:result.data||[],
      //       page,
      //       searchFlag:false,
      //       pageSize:size,
      //     });
      // }else{
      //   this.setState({
      //     searchFlag:false
      //   })
      //   message.error(result.msg)
      // }

    }

    // doSearch(){
    //   let {page,pageSize} = this.state;
    //   this.doFetch(page,pageSize);
    // }









    // onClickRemark(record){
    //   this.setState({
    //     remarkVisibility:true,
    //   })
    // }


    // onSearch(searchCondition){
    //   let {search} = this.state;
    //   search = {...searchCondition}
    //   this.setState({
    //     search,
    //     filterConditionVisibility:false,
    //   })
    // }

    // onReset(){
    //   this.setState({
    //     search:{},
    //     filterConditionVisibility:false
    //   })
    // }

    exportTable(e){
      if (e.key == "ALL") {
        
      }else if (e.key == "SELECTED") {
        
      }else{

      }
    }

    onChangeType(type,value){


      switch(type) {
        case ANALYZE_TABLE_TYPE[6]://回收款
          this.getRecycleAmount(value);
          break;
        case ANALYZE_TABLE_TYPE[7]://期末资产
          this.getEndtermAsset(value);
          break;
      }
    }

    //根据type获取回收款
    async getRecycleAmount(type){
      let {data,period} = this.state;
      let result = await api('/property/getRecycleAmout/list',{type,period});

      if (result.success) {
        data.recycleAmount = result.data;
        this.setState({
          data,
          recycleAmountSubType:type,
        })
      }else{
        message.error(result.message);
      }
    }

    //根据type获取集中度分析
    async getEndtermAsset(type){
      let {data,period} = this.state;
      let result = await api('/property/getEndtermAsset/list',{type,period});

      if (result.success) {
        data.endAsset = result.data;
        this.setState({
          data,
          endTermAssetSubType:type,
        })
      }else{
        message.error(result.message);
      }
    }


    formatNumber(num) {
      return (num / 10000).toFixed(2).toString();
    }

    toMoneyFormat(number){
       let s = this.formatNumber(number);
        if(/[^0-9\.]/.test(s)) return "invalid value";
        s=s.replace(/^(\d*)$/,"$1.");
        s=(s+"00").replace(/(\d*\.\d\d)\d*/,"$1");
        s=s.replace(".",",");
        var re=/(\d)(\d{3},)/;
        while(re.test(s))
            s=s.replace(re,"$1,$2");
        s=s.replace(/,(\d\d)$/,".$1");
        return s.replace(/^\./,"0.")
    }

    onChangePeriod(value){
      this.setState({
        loading:true,
      })
      this.doFetch(value);
    }

    changePath(path){
      let {changepath} = this.props;
      console.log('test',this.props);
      // if (path && changepath) {
      //   changepath(path);
      // }
    }

    
    //分页
    // toPage({current:page,pageSize,total}){
    //   page = page - 1;
    //   this.doFetch(page,pageSize);
    // }

    // changePageSizer(current,size){
    //   current = current - 1;
    //   this.doFetch(current,size);
    // }

    
    // quickJumper(pageNumber,pageSize){
    //   pageNumber = pageNumber - 1;
    //   this.doFetch(pageNumber,pageSize);
    // }

    // getExportMenu(){
    //   return (
    //       <Menu onClick={this.exportTable.bind(this)}>
    //         <Menu.Item key="ALL">导出全部</Menu.Item>
    //         <Menu.Item key="SELECTED">导出选中</Menu.Item>
    //       </Menu>
    //     )
    // }
    
    render() {

        var {list, page,total,searchFlag,departmentList,search,pageSize,endTermAssetSubType,recycleAmountSubType}=this.state;
        let {
          assetReport,
          currentHappen,
          recycleAmount,
          endAsset,
          endAccumulate,
        }=this.state.data
        return (
          <Spin spinning={this.state.loading}>
            <div className="bgWhite marginL25 marginB40">
                <div style={{"padding":"20px","background":"#F7F7F7"}}>
                    <div className="containerWithBorder paddingT15 bgWhite">
                        <div className="marginL15 marginR15">
                            <div style={{"float":"left",margintTop:"10px"}}>资产报告</div>
                            <div className="text-right">
                                <Select 
                                  onChange={this.onChangePeriod.bind(this)}
                                  style={{width:230}}
                                  defaultValue="3"
                                >
                                  <Option key="3" value="3">第3期（2018-09-01 至 2018-11-30）</Option>
                                  <Option key="2" value="2">第2期（2018-06-01 至 2018-08-31）</Option>
                                  <Option key="1" value="1">第1期（2018-03-01 至 2018-05-31）</Option>
                                </Select>
                                <Button
                                  className='marginL10'
                                >导出<Icon type="download" /></Button>
                            </div>
                        </div>

                        <Row className="marginT20">
                            <Col 
                                span={4} 
                                className="containerWithRightBorder containerWithTopBorder padding15" 
                                
                            >
                                <div className="marginL15">
                                    <p>存续合同数</p>
                                    <p style={{fontSize:26}}>{
                                      assetReport.existenceContract?
                                        assetReport.existenceContract
                                      :
                                        "0"
                                    }<span style={{fontSize:14}}>个</span></p>
                                    <p>期初{
                                      assetReport.existenceContract_beginning?
                                        assetReport.existenceContract_beginning
                                      :
                                        "0"
                                    }个</p>
                                </div>
                            </Col>
                            <Col 
                                span={4} 
                                className="containerWithRightBorder containerWithTopBorder padding15" 
                                style={{paddingRight:"15px"}}
                            >
                                <div className="marginL15">
                                    <p>基础资产笔数</p>
                                    <p style={{fontSize:26}}>{
                                      assetReport.countBaseAsset?
                                        assetReport.countBaseAsset
                                      :
                                        "0"
                                    }<span style={{fontSize:14}}>笔</span></p>
                                    <p>期初{
                                      assetReport.countBaseAsset_beginning?
                                        assetReport.countBaseAsset_beginning
                                      :
                                        "0"
                                    }个</p>
                                </div>
                            </Col>
                            <Col 
                                span={4} 
                                className="containerWithRightBorder containerWithTopBorder padding15" 
                                style={{paddingRight:"15px"}}
                            >
                                <div className="marginL15">
                                    <p>基础资产金额</p>
                                    <p style={{fontSize:26}}>{
                                      assetReport.baseAssetMoney?
                                        this.toMoneyFormat(assetReport.baseAssetMoney)
                                      :
                                        "0.00"
                                    }<span style={{fontSize:14}}>万元</span></p>
                                    <p>期初{
                                      assetReport.baseAssetMoney_beginning?
                                        assetReport.baseAssetMoney_beginning
                                      :
                                        "0"
                                    }笔</p>
                                </div>
                            </Col>
                            <Col 
                                span={4} 
                                className="containerWithRightBorder containerWithTopBorder padding15" 
                                style={{paddingRight:"15px"}}
                            >
                                <div className="marginL15">
                                    <p>逾期资产金额</p>
                                    <p style={{fontSize:26}}>{
                                      assetReport.sumOverdueAssetMoney?
                                        this.toMoneyFormat(assetReport.sumOverdueAssetMoney)
                                      :
                                        "0.00"
                                    }<span style={{fontSize:14}}>万元</span></p>
                                    <p>逾期比例{
                                      assetReport.overdueRate?
                                        assetReport.overdueRate
                                      :
                                        "0"
                                    }%</p>
                                </div>
                            </Col>
                            <Col 
                                span={4} 
                                className="containerWithRightBorder containerWithTopBorder padding15" 
                                style={{paddingRight:"15px"}}
                            >
                                <div className="marginL15">
                                    <p>违约资产金额</p>
                                    <p style={{fontSize:26}}>{
                                      assetReport.sumBreakAssetMoney?
                                        this.toMoneyFormat(assetReport.sumBreakAssetMoney)
                                      :
                                        "0.00"
                                    }<span style={{fontSize:14}}>万元</span></p>
                                    <p>违约比例{
                                      assetReport.breakRate?
                                        assetReport.breakRate
                                      :
                                        "0"
                                    }%</p>
                                </div>
                            </Col>
                            <Col 
                                span={4} 
                                className="containerWithTopBorder padding15" 
                                style={{paddingRight:"15px"}}
                            >
                                <div className="marginL15">
                                    <p>闲置资金金额</p>
                                    <p style={{fontSize:26}}>{
                                      assetReport.sumUnusedAssetMoney?
                                        this.toMoneyFormat(assetReport.sumUnusedAssetMoney)
                                      :
                                        "0.00"
                                    }<span style={{fontSize:14}}>万元</span></p>
                                    <p>闲置比例{
                                      assetReport.unusedRate?
                                        assetReport.unusedRate
                                      :
                                        "0"
                                    }%</p>
                                </div>
                            </Col>
                        </Row>
                    </div>

                    <Table
                        columns={this.getCurrentPhaseColumns()}
                        dataSource={currentHappen}
                        title={() => {
                                return (<div className="marginL15">当期发生</div>)
                            }
                        }
                        className="containerWithTopBorder containerWithRightAndLeftBorder marginT20 bgWhite"
                        pagination={false}
                        rowKey={(record,index) => index}
                    >
                    </Table>

                    <DataAnalyzeTable
                        type={ANALYZE_TABLE_TYPE[6]}
                        list={recycleAmount}
                        subType={recycleAmountSubType}
                        onChangeType={this.onChangeType.bind(this,ANALYZE_TABLE_TYPE[6])}
                    />

                    <DataAnalyzeTable
                        type={ANALYZE_TABLE_TYPE[7]}
                        list={endAsset}
                        subType={endTermAssetSubType}
                        onChangeType={this.onChangeType.bind(this,ANALYZE_TABLE_TYPE[7])}
                        changePath={this.changePath.bind(this)}
                    />

                    <Table
                        columns={this.getEndTermTotalColumns()}
                        dataSource={endAccumulate}
                        title={() => {
                                return (<div className="marginL15">期末累计</div>)
                            }
                        }
                        className="containerWithTopBorder containerWithRightAndLeftBorder marginT20 bgWhite marginB25"
                        pagination={false}
                        rowKey={(record,index) => index}
                    >
                    </Table>

                </div>
            </div>
          </Spin>
        );
    }

    getCurrentPhaseColumns(){
      let {session} = this.state;
      let columns = [
            {
              title:'',
              dataIndex:'event',
              key:'event',
            },
            {
              title: '金额',
              dataIndex: 'amount',
              key: 'amount',
            }, {
              title: '金额占比',
              dataIndex: 'amount_rate',
              key: 'amount_rate',
            }, {
              title: '笔数',
              dataIndex: 'count',
              key: 'count',
            },{
              title: '笔数占比',
              dataIndex: 'count_rate',
              key: 'count_rate',
            }
        ];

        return columns
    }

    getEndTermTotalColumns(){
      let {session} = this.state;
      let columns = [
            {
              title:'',
              dataIndex:'acc_type',
              key:'acc_type',
            },
            {
              title: '金额',
              dataIndex: 'amount',
              key: 'amount',
            }, {
              title: '金额占比',
              dataIndex: 'amount_rate',
              key: 'amount_rate',
            }, {
              title: '笔数',
              dataIndex: 'count',
              key: 'count',
            },{
              title: '笔数占比',
              dataIndex: 'count_rate',
              key: 'count_rate',
            }
        ];

        return columns
    }

    
}

RedeemReportList.contextTypes= { router: React.PropTypes.object.isRequired};
